package com.hamll.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.utils.StringUtils;
import com.hamll.search.pojo.ItemDoc;
import com.hamll.search.pojo.RequestParams;
import com.hamll.search.service.SearchService;
import com.hmall.common.client.ItemClient;
import com.hmall.common.dto.Item;
import com.hmall.common.dto.PageDTO;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private ItemClient itemClient;

    @Override
    public PageDTO<ItemDoc> findByPage(RequestParams requestParams) {
        try {
            Integer page = requestParams.getPage();
            Integer size = requestParams.getSize();
            String sortBy = requestParams.getSortBy();
            SearchRequest request = new SearchRequest("hamll");
            getQuery(request, requestParams);
            request.source().from((page - 1) * size).size(size);
            if ("price".equals(sortBy)){
                request.source().sort(sortBy, SortOrder.ASC);
            }
            if ("sold".equals(sortBy)){
                request.source().sort(sortBy,SortOrder.DESC);
            }
            request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));
            SearchResponse search = client.search(request, RequestOptions.DEFAULT);
            return getPageDto(search);
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }

    @Override
    public List<String> getSuggest(String key) {
        try {
            SearchRequest request = new SearchRequest("hamll");
            request.source().suggest(
                    new SuggestBuilder().addSuggestion("mySuggestion",
                            SuggestBuilders.completionSuggestion("suggestion").
                                    prefix(key).skipDuplicates(true).size(20))
            );
            SearchResponse search = client.search(request, RequestOptions.DEFAULT);
            CompletionSuggestion mySuggestion = search.getSuggest().getSuggestion("mySuggestion");
            List<CompletionSuggestion.Entry.Option> options = mySuggestion.getOptions();
            List<String> list = new ArrayList<>();
            for (CompletionSuggestion.Entry.Option option : options) {
                String s = option.getText().toString();
                list.add(s);
            }
            return list;
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }

    @Override
    public Map<String, List<String>> filters(RequestParams params) {
        try {
            SearchRequest request = new SearchRequest("hamll");
            getQuery(request,params);
            request.source().size(0);
            request.source().aggregation(AggregationBuilders.terms("brandAgg").field("brand"));
            request.source().aggregation(AggregationBuilders.terms("categoryAgg").field("category"));
            SearchResponse search = client.search(request, RequestOptions.DEFAULT);
            Aggregations aggregations = search.getAggregations();
            List<String> brandAgg = getAgg(aggregations, "brandAgg");
            List<String> categoryAgg = getAgg(aggregations, "categoryAgg");
            Map<String, List<String>> map = new HashMap<>();
            map.put("brand",brandAgg);
            map.put("category",categoryAgg);
            return map;
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }

    @Override
    public void insert(Long id) {
        try {
            Item item = itemClient.findByID(id);
            if (item==null)return;
            IndexRequest request = new IndexRequest("hamll").id(id.toString());
            ItemDoc itemDoc = new ItemDoc(item);
            request.source(JSON.toJSONString(itemDoc), XContentType.JSON);
            client.index(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }

    @Override
    public void delete(Long id) {
        try {
            DeleteRequest request = new DeleteRequest("hamll").id(id.toString());
            client.delete(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }

    private List<String> getAgg(Aggregations aggregations,String aggName) {
        Terms brandAgg = aggregations.get(aggName);
        List<? extends Terms.Bucket> buckets = brandAgg.getBuckets();
        List<String> list = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            String key = bucket.getKeyAsString();
            list.add(key);
        }
        return list;
    }

    private void getQuery(SearchRequest request, RequestParams requestParams) {
        String key = requestParams.getKey();
        String brand = requestParams.getBrand();
        String category = requestParams.getCategory();
        Long maxPrice = requestParams.getMaxPrice();
        Long minPrice = requestParams.getMinPrice();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (StringUtils.isBlank(key)) {
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        } else {
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", key));
        }
        if (!StringUtils.isBlank(brand)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand", brand));
        }
        if (!StringUtils.isBlank(category)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("category", category));
        }
        if (minPrice != null && maxPrice != null) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(minPrice * 100).lte(maxPrice * 100));
        }
        FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(
                boolQueryBuilder, new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD",true),
                                ScoreFunctionBuilders.weightFactorFunction(10)
                        )
                }
        ).boostMode(CombineFunction.SUM);
        request.source().query(functionScoreQuery);
    }

    private PageDTO<ItemDoc> getPageDto(SearchResponse search) {
        SearchHit[] hits = search.getHits().getHits();
        List<ItemDoc> list = new ArrayList<>();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            ItemDoc itemDoc = JSON.parseObject(sourceAsString, ItemDoc.class);
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (!CollectionUtils.isEmpty(highlightFields)) {
                HighlightField highlightField = highlightFields.get("name");
                if (highlightField != null){
                    String highName = highlightField.getFragments()[0].toString();
                    itemDoc.setName(highName);
                }
            }
            list.add(itemDoc);
        }
        long total = search.getHits().getTotalHits().value;
        return new PageDTO<ItemDoc>(total, list);
    }
}
